import { Text, View, FlatList, StyleSheet, TouchableHighlight, ActivityIndicator } from 'react-native'
import React, { useState, useEffect } from 'react'
import { pTx } from "../../utils/dimensions"
import { connect } from 'react-redux'
import { Toast } from '@pingtou/rn-vant';
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"
import Avatar from "../../components/avatar"
import httpApi from "../../api"

const getData = (groupMsgLis, groupMembers) => {
    const some = [];
    let MsgLis = groupMsgLis.filtered(`MT >= 61 and MT <= 63`).sorted('T', true)
    MsgLis.forEach(el => {
        if (!some.some(e => e.F == el.F)) {
            // const isFriend = groupMembers.find(item => item.G == el.F)
            some.push({ ...el, loading: false });
        }
    });
    return some
}

const GroupJoinReply = (props) => {
    const [group] = useState(props.route.params)
    const realm = useRealm();
    const [list, setList] = useState([])
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const groupInfo = useQuery(schemaName.GroupInfo, Info => {
        return Info.filtered(`Id == ${group.G} and UserId == ${userInfo.Id}`);
    })[0];
    const groupMembers = useQuery(schemaName.GroupMembers, groupMsg => {
        return groupMsg.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`)
    })
    const groupMsgLis = useQuery(schemaName.GroupMsgLis, groupMsg => {
        return groupMsg.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`).sorted('T', true)
    })
    useEffect(() => {
        setList(getData(groupMsgLis))
    }, []);


    useEffect(() => {
        let MsgLis = groupMsgLis.filtered(`Unread == 1 and MT >= 60 `).sorted('T', true)
        realm.write(() => {
            for (const msg of MsgLis) {
                msg.Unread = 0
            }
        })
    }, [])

    const onDogsChange = (dogs, changes) => {
        changes.insertions.forEach((index) => {
            setList(getData(groupMsgLis))
        });
    }

    useEffect(() => {
        groupMsgLis.addListener(onDogsChange);
        return () => {
            groupMsgLis.removeListener(onDogsChange);
        };
    }, []);



    const sendGroupJoinReply = async (item, index) => {
        try {
            if (item.loading) return
            setList(prev => prev.map((element, idx) => {
                if (idx === index) {
                    item.loading = true
                    return element
                }
                return element
            }))
            const res = await httpApi.sendGroupJoinReply({ id: item.M.split(' ')[0], msgType: 62 })
            if (res.code == 20) {
                props.navigation.goBack()
            } else {
                Toast(res.message)
            }
        } catch (error) {
        }
        setList(prev => prev.map((element, idx) => {
            if (idx === index) {
                item.loading = false
                return element
            }
            return element
        }))
    }
    return (
        <FlatList
            style={{ flex: 1, backgroundColor: "#fff" }}
            renderItem={({ item, index }) => {
                return (
                    <View style={[styles.li, styles.flexDirectionRow]}>
                        <View style={[styles.row, styles.flexDirectionRow]}>
                            <Avatar style={[styles.avatar]} source={{ uri: item.P }}></Avatar>
                            <View style={styles.cell}>
                                <Text style={styles.name} onPress={() => this.clicks(1)}>{item.R}</Text>
                                {item.M?.split(' ')[1] && <Text style={styles.text} onPress={() => this.clicks(1)}>{item.M.split(' ')[1]}</Text>}
                            </View>
                        </View>
                        {item.MT == 61 ?
                            <View style={[styles.flexDirectionRow, styles.setUp]}>
                                {item.loading && <ActivityIndicator size={pTx(12)} />}
                                < Text style={[styles.styleText]} onPress={() => sendGroupJoinReply(item, index)}>确认</Text>
                            </View>
                            :
                            <Text style={[styles.styleText]} onPress={() => sendGroupJoinReply(item, index)}>已添加</Text>
                        }
                    </View >
                )
            }}
            data={list}
            keyExtractor={(item, index) => index}
        />
    )
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {

}

export default connect(mapStateToProps, mapDispatchToProps)(GroupJoinReply)

const styles = StyleSheet.create({
    walletHeaderView: {
        height: pTx(60),
        paddingHorizontal: pTx(15),
        paddingRight: pTx(8),
    },
    flexDirectionRow: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
    },
    li: {
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(10),
        borderBottomColor: "rgba(175,181,189,0.15)",
        borderBottomWidth: 1
    },
    avatar: {
        width: pTx(30),
        height: pTx(30),
        borderRadius: pTx(6),
    },
    cell: {
        marginLeft: pTx(12),
    },
    name: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
    setUp: {
        paddingHorizontal: pTx(10),
        paddingVertical: pTx(5),
        backgroundColor: 'rgba(51, 225, 144, 1)',
        borderRadius: pTx(5),
    },
    styleText: {
        marginLeft: pTx(3),
        fontSize: pTx(12),
    },
    confirm: {
        backgroundColor: 'rgba(51, 225, 144, 1)',
    }
})